<?php
// 常量相关
const CURRENCY_COIN = 0;// 金币
const CURRENCY_VN = 1;// 越南盾
const CURRENCY_SHIB = 2;// 狗狗币
const CURRENCY_DIAMOND = 3;// 钻石
const MONEY_TYPE_BALANCE = 0; // 可用余额
const MONEY_TYPE_WITHDRAWAL = 1; // 已提现金额
const MONEY_INCOME = 0; // 收入
const MONEY_EXPEND = 1; // 支出
const MONEY_FROZEN = 2; // 冻结
const MONEY_RECORD_STATE_FIELD = 0; // 失败
const MONEY_RECORD_STATE_HANDLE = 1; // 操作中
const MONEY_RECORD_STATE_SUCCESS = 2; // 成功
const MONEY_RECORD_STATE_COMPLETE = 3; // 交易完成
const MONEY_RECORD_METHOD_DUTY = 0; //签到
const MONEY_RECORD_METHOD_INVITE = 1; //邀请码奖励
const MONEY_RECORD_METHOD_WITHDRAWAL = 2; //提现
const MONEY_RECORD_METHOD_CONVERT = 3; //货币兑换
const MONEY_RECORD_METHOD_READ = 4; //阅读新闻任务
const MONEY_RECORD_METHOD_CHEST = 5; //宝箱任务
const MONEY_RECORD_METHOD_GOLD = 6; //金币浮层任务
const MONEY_RECORD_METHOD_DOUBLE = 7; //双倍奖励
const MONEY_RECORD_METHOD_FRIEND = 8; //好友登录
const MONEY_RECORD_METHOD_FRIEND3 = 9; //好友登录3天
const MONEY_RECORD_METHOD_FRIEND7 = 10; //好友登录7天
const MONEY_RECORD_METHOD_NEW_USER = 11; //新人专享
const MONEY_RECORD_METHOD_REFUND = 12; //提现失败退回
const MONEY_RECORD_METHOD_LOTTERY = 13; //转盘
const MONEY_RECORD_METHOD_LOTTERY10 = 14; //转盘10次
const MONEY_RECORD_METHOD_LOTTERY_CHEST = 15; //转盘宝箱
const MONEY_RECORD_METHOD_NEWS10 = 16; //新闻10次
const MONEY_RECORD_METHOD_CHEST10 = 17; //宝箱10次
const MONEY_RECORD_METHOD_CASH = 18; //提现1次
const MONEY_RECORD_METHOD_VIDEO_AD = 19; //视频广告
const MONEY_RECORD_METHOD_CLICK_AD = 20; //点广告赚金币
const MONEY_RECORD_METHOD_DOWN_AD = 21; //看广告并试玩


// 应用公共文件
if (!function_exists('pdie')) {
    /**
     * 数据打印
     * @param $mix
     * @param bool $die
     */
    function pdie($mix, bool $die = false) {
        echo '<pre>';
        print_r($mix);
        empty($die) || die('</pre>');
    }
}

if (!function_exists('shibRate')) {
    /**
     * 获取shib汇率（30分钟更新一次）
     * @return int|mixed
     * @throws \app\common\RootException
     */
    function shibRate() {
        $cacheKey = 'shibRate';
        $cacheData = cache($cacheKey);
        $apiUrl = 'https://api-market.qrydq.com/api/market'; // SHIB汇率接口地址
        // 缓存汇率
        if (empty($cacheData) || $cacheData['expire'] < time()) {
            // 获取汇率
            $respone = httpSend($apiUrl);
            // 过期时间
            $expireTime = time() + 3600;
            if (isset($respone['code'])) {
                $transferRate = $respone['code'] == 200 ? $respone['data']['value'] : 0;
                // 更新缓存
                empty($transferRate) || cache($cacheKey, ['rate' => $transferRate, 'expire' => $expireTime]);
            } else {
                // 没获取到用最后一次获取到的缓存
                cache($cacheKey, ['rate' => $cacheData['rate'] ?? 0.00002079, 'expire' => $expireTime]);
            }
            $cacheData = cache($cacheKey);
        }
        return $cacheData['rate'];
    }
}

if (!function_exists('moneyRecordAdd')) {
    /**
     * 记录资金流水
     * @param array $params
     * @param bool $tryCatch
     * @return \app\common\model\MoneyRecordModel|\think\Model|void
     * @throws \app\common\RootException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function moneyRecordAdd(array $params, bool $tryCatch = false)
    {
        $service = new \app\common\service\MoneyRecordService();
        return $tryCatch ? $service->addCatch($params) : $service->add($params);
    }
}

if (!function_exists('transferAmount')) {
    /**
     * 提现金额转换
     * @return int|mixed
     * @throws \app\common\RootException
     */
    function transferAmount(int $coin, int $currency) {
        if (empty($currency)) {
            $transferAmount = $coin * config('rule.vdRate'); // 越南盾
        } else {
            $transferAmount = floor($coin * 0.00003 / shibRate() / config('rule.usdt')); // SHIB
        }
        return $transferAmount;
    }
}

if (!function_exists('betweenDate')) {
    /**
     * 时间范围转数组
     * @param string $date 日期范围(2021-09-01 ~ 2021-09-27)
     * @param string $separator 分隔符:默认(~)
     * @return false|string[]
     */
    function betweenDate(string $date, string $separator = '~') {
        $dateArr = explode($separator, $date);
        $dateArr[0] .= ' 00:00:00';
        empty($dateArr[1]) || $dateArr[1] .= ' 23:59:59';
        return [dateTimeFlipChange(trim($dateArr[0])), dateTimeFlipChange(trim($dateArr[1]))];
    }
}

if (!function_exists('userAgent')) {
    /**
     * 客户端来源标识
     * @return int
     */
    function userAgent()
    {
        // 客户端标识
        $userAgent = strtolower(request()->header('user_agent'));
        // IOS标识
        strpos($userAgent, 'ios') !== false && $platform = 0;
        // 安卓标识
        strpos($userAgent, 'android') !== false && $platform = 1;
        // 返回
        return $platform ?? 1;
    }
}

if (!function_exists('siteDomain')) {
    /**
     * 站点域名
     * @return string
     */
    function siteDomain() {
        $server = app('request')->server();
        return $server['REQUEST_SCHEME'] . '://' . $server['HTTP_HOST'] . '/';
    }
}

if (!function_exists('realImgUrl')) {
    /**
     * 真实URL地址
     * @param string $path 相对地址
     */
    function realImgUrl(string $path) {
        return siteDomain() . $path;
    }
}

if (!function_exists('condition')) {
    /**
     * 筛选条件判断
     * @param string $param
     * @return bool
     */
    function condition($param) {
        return in_array(trim($param), [null]) ? false : true;
    }
}


if (!function_exists('httpSend')) {
    /**
     * 发送HTTP请求
     * @param $url
     * @param array $params
     * @param string $method
     * @param array $header
     * @param false $multi
     * @return mixed
     * @throws \app\common\RootException
     */
    function httpSend($url, $params = [], $method = 'GET', $header = array(), $multi = false) {
        $opts = array(
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_HTTPHEADER     => $header
        );
        switch(strtoupper($method)) {
            case 'GET':
                $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
                break;
            case 'POST':
                $params = $multi ? $params : http_build_query($params);
                $opts[CURLOPT_URL] = $url;
                $opts[CURLOPT_POST] = 1;
                $opts[CURLOPT_POSTFIELDS] = $params;
                break;
            default:
                throw new \app\common\RootException('不支持的请求方式！');
        }

        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $data  = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        empty($error) || exit('请求发生错误：' . $error);

        return  json_decode($data, true);
    }
}

if (!function_exists('httpPostJson')) {
    /**
     * 发送postJson请求
     * @param string $url
     * @param array $params
     * @param array $headerData
     * @return array
     */
    function httpPostJson(string $url, array $params, array $headerData = []) {
        // 初始化
        $ch = curl_init();
        // 请求参数
        $postData = json_encode($params);
        // 默认header头信息
        $header = ['Content-Type:application/json; charset=utf-8', 'Content-Length:' . strlen($postData)];
        // 处理headerData数据
        empty($headerData) || array_walk($headerData, function (&$row, $key) {
            $row = "{$key}:{$row}";
        });
        // 数据处理
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array_merge($header, array_values($headerData)));
        // 发送请求
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        // 响应结果
        return ['code' => $httpCode, 'data' => json_decode($response, true)];
    }
}


if (!function_exists('writeLog')) {
    /**
     * 写入日志
     * @param array $data
     * @param string $type
     */
    function writeLog(array $data, string $type = 'normal') {
        \think\facade\Log::channel($type)->write(json_encode($data, JSON_UNESCAPED_UNICODE) . PHP_EOL);
    }
}

if (!function_exists('generateSn')) {
    /**
     * 生成序列号
     * @param string $type
     * @return string
     */
    function generateSn(string $type = '')
    {
        return $type . date('YmdHis') . mt_rand(1000, 9999);
    }
}


/**
 * 过滤HTML标签
 */
if (!function_exists('htmlFilterLabel')) {
    function htmlFilterLabel(string $html) {
        return preg_replace("/<([a-zA-Z]+)[^>]*>/","<\\1>",$html);
    }
}

if (!function_exists('mbHashClient')) {
    /**
     * 用户哈希缓存客户端
     * @return \redis\RedisClient
     */
    function mbHashClient() {
        return new \redis\MemberHash(config('redis.db.member'));
    }
}
if (!function_exists('generateInvite')) {
    /**
     * 生成邀请码
     */
    function generateInvite() {
        $cacheName = 'generateInvite';
        if (!$invitePool = cache($cacheName)) {
            $offset = 1000;// 每次生成邀请码的数量
            $firstInvite = 10000000;// 起始邀请码
            // 最大的邀请码
            $maxInvite = \app\common\model\MemberModel::Max('invite');
            // 开始邀请码
            $startInvite = $maxInvite ? $maxInvite - $firstInvite : 1;
            // 结束邀请码
            $endInvite = $offset + $startInvite;
            for ($i = $startInvite; $i < $endInvite; $i++) {
                $invitePool[] = $firstInvite + $i + 1;
            }
            shuffle($invitePool);// 打乱邀请码顺序
        }
        // 邀请码
        $invite = array_pop($invitePool);
        // 邀请码缓存池
        cache($cacheName, $invitePool);
        // 返回邀请码
        return $invite;
    }
}
if (!function_exists('arrColumn')) {
    /**
     * 处理数组
     * @param array $data
     * @param string $field
     * @return mixed
     */
    function arrColumn(array $data, string $field) {
        empty($data) || array_walk($data, function ($row) use (&$returnData, $field) {
            empty($row[$field]) || $returnData[$row[$field]][] = $row;
        });
        return $returnData ?? $data;
    }
}

if (!function_exists('dateTimeChange')) {
    function dateTimeChange($dateTime, $format = 'Y-m-d H:i:s')
    {
        if(!$dateTime)return '';
        $config = 'Asia/Shanghai';
        $befConfig = date_default_timezone_get();
        if($config == $befConfig) {
            return $dateTime;
        }
        $time = strtotime($dateTime);
        date_default_timezone_set($config);
        $returnStr = date($format,$time);
        date_default_timezone_set($befConfig);
        return $returnStr;
    }
}


if (!function_exists('dateTimeFlipChange')) {

    function dateTimeFlipChange($dateTime, $format = 'Y-m-d H:i:s')
    {
        if(!$dateTime)return '';
        $config = 'Asia/Shanghai';
        $befConfig = date_default_timezone_get();
        if($config == $befConfig) {
            return $dateTime;
        }
        date_default_timezone_set($config);
        $time = strtotime($dateTime);
        date_default_timezone_set($befConfig);
        $returnStr = date($format,$time);
        return $returnStr;
    }
}

if (!function_exists('realMoney')) {
    /**
     * 金额格式化
     * @param int $coin
     * @param string $unit
     * @return string
     */
    function realMoney($coin)
    {
        switch (env('app.default_timezone')) {
            case 'Asia/Ho_Chi_Minh':
                $coin = $coin . 'đ';
                break;
            case 'America/Sao_Paulo':
                $coin = 'R$' . $coin;
                break;
            default:
                $coin = $coin;
        }
        return $coin;
    }
}